package mallindex

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/api/internal/utils/parse"
	"mall/service/promotion/rpc/promotionclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetCouponListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetCouponListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCouponListLogic {
	return &GetCouponListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetCouponListLogic) GetCouponList(
	req *types.GetCouponListReq,
	headers *[]*types.Header,
) (resp *types.CouponListResp, err error) {

	// var limit uint32 = uint32(l.svcCtx.Config.Query.DefaultAmount)
	// if req.Limit != nil && *req.Limit > 0 {
	// 	limit = *req.Limit
	// } else {
	// 	limit = uint32(l.svcCtx.Config.Query.DefaultAmount)
	// }
	// var offset uint32
	// if req.Offset != nil && *req.Offset > 0 {
	// 	offset = *req.Offset
	// }

	//是否采用预加载
	// var preload string = "coupon:Id,Title"
	// var filters []string
	// filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	// if req.Type != nil {
	// 	filters = append(filters, "Type,equalTo:"+strconv.FormatInt(int64(*req.Type), 10))
	// } else {
	// 	filters = append(filters, "Type,equalTo:"+strconv.FormatInt(int64(globalkey.SettingCouponTypeDefault), 10))
	// }

	//没有status这个字段

	// var status uint32
	// if req.Status != nil {
	// 	status = *req.Status + 1
	// }

	var (
		offset          uint32
		limit           uint32
		filters         []string
		hasNextPage     bool
		hasPreviousPage bool
		respHeaders     []*types.Header
	)
	userId := jwt.GetUserId(l.ctx)
	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	//构造查询条件
	filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	if req.Type != nil {
		filters = append(filters, "Type,equalTo:"+strconv.Quote(*req.Type))
	} else {
		//筛选启用的优惠券，默认状态SettingCouponTypeDefault
		filters = append(filters, "Type,equalTo:"+strconv.FormatInt(int64(globalkey.SettingCouponTypeDefault), 10)) //0->未使用；1->已使用；2->已过期；3->删除；10->冻结，默认0
	}

	//获取baselist请求，返回放在res
	res, err := l.svcCtx.PromotionRpc.GetCouponTemlateList(l.ctx, &promotionclient.BaseListReq{
		Offset: offset,
		Limit:  limit,
		// Preload:    pointy.GetPointer(preload),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		logx.Errorw("获取优惠券失败", logx.Field("err", err.Error()))
		return nil, err
	}

	//判定最后一页和首页
	if res.HasNextPage != nil && *res.HasNextPage > 0 {
		hasNextPage = true
	}
	if res.HasPreviousPage != nil && *res.HasPreviousPage > 0 {
		hasPreviousPage = true
	}

	//构造resp：1.基础信息
	resp = &types.CouponListResp{
		BaseListInfo: types.BaseListInfo{
			Current:         page,
			PageSize:        pageSize,
			HasNextPage:     hasNextPage,
			HasPreviousPage: hasPreviousPage,
		},
	}

	//2.list信息
	for _, v := range res.List {
		resp.List = append(resp.List, &types.TmpCouponInfo{
			Id:    v.Id,
			Title: v.Name,
		})
	}

	//3.header信息
	respHeaders = append(respHeaders, &types.Header{
		Key:   "x-class",
		Value: "com.djx.appview.MallIndexPage",
	})
	*headers = respHeaders

	return resp, nil
}
